package com.hly.wms.service.impl;

import com.hly.common.constant.WareConstant;
import com.hly.wms.entity.PurchaseEntity;
import com.hly.wms.feign.ProductFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.common.utils.PageUtils;
import com.hly.common.utils.Query;

import com.hly.wms.dao.PurchaseDetailDao;
import com.hly.wms.entity.PurchaseDetailEntity;
import com.hly.wms.service.PurchaseDetailService;


@Service("purchaseDetailService")
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailDao, PurchaseDetailEntity> implements PurchaseDetailService {
    @Autowired
    private ProductFeign productFeign;

    @Override
    public boolean save(PurchaseDetailEntity entity) {
        if(productFeign.getBySkuId(entity.getSkuId()) != null){
            entity.setStatus(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode());
        }else {
            entity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
        }
        return retBool(baseMapper.insert(entity));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String wareInfo = (String) params.get("wareInfo");
        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(i -> i.eq("purchase_id",key).or()
                    .eq("sku_id",key)
                    .or()
                    .eq("sku_num",key)
                    .or()
                    .eq("sku_price",key));
        }
        if(StringUtils.isNotEmpty(wareInfo)){
            wrapper.eq("ware_id",wareInfo);
        }
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }

        IPage<PurchaseDetailEntity> page = this.page(
                new Query<PurchaseDetailEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<PurchaseDetailEntity> listDetailByPurchaseId(String id) {
        QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("purchase_id",id);
        return this.list(wrapper);
    }

}